import { Injectable } from '@nestjs/common';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class SmsService {
  constructor(
    private readonly redisService: RedisService,
  ) {}

  private generateCode(): string {
    return Math.random().toString().slice(-6);
  }

  async sendCode(phone: string): Promise<string> {
    const code = this.generateCode();
    const key = `sms:${phone}`;
    
    console.log('Saving SMS code to Redis:', { key, code });
    await this.redisService.set(key, code, 5 * 60); // 改为5分钟（300秒）
    
    console.log(`向 ${phone} 发送验证码: ${code}`);
    
    return code;
  }

  async verifyCode(phone: string, code: string): Promise<boolean> {
    const key = `sms:${phone}`;
    // 错误：this.redis 应该是 this.redisService
    const savedCode = await this.redisService.get(key);
    
    if (savedCode === code) {
      // 错误：this.redis 应该是 this.redisService
      await this.redisService.del(key);
      return true;
    }
    
    return false;
  }
}





